<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import { updateArticleService, deleteArticleService } from '@/api/article/article.js'
import { sysArticleListService,categoryListByUserIdService } from '@/api/system/article.js'
import {Plus} from '@element-plus/icons-vue'
import {useTokenStore} from '@/stores/token.js'
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from "dayjs";


const tokenStore=useTokenStore()
//文章分类数据模型
const categorys = ref([])
//文章列表数据模型
const articles = ref([])
//请求参数
const queryParams=ref({
  pageNum:1,//当前页
  pageSize:5,//每页条数
  title:'',
  state:'',
  createTime:'',
  categoryName:'',
  username:''
})
//总条数
const total = ref(20)
//控制抽屉是否显示
const visibleDrawer = ref(false)
//文章数据模型
const articleModel = ref({
  title: '',
  categoryId:'',
  coverImg: '',
  content:'',
  state:'',
  username:''
})
//抽屉标题
const title=ref('')
//控制图片放大框
const dialogVisible=ref(false)
//当前放大图片地址
const currentImage=ref('')
//搜索表单引用
const queryForm=ref()


//显示图片放大框
const showImageDialog=(imageUrl)=>{
  dialogVisible.value=true
  currentImage.value=imageUrl
}

//日期格式化
const formatDate=(date)=>{
  let today = new Date();
  let target = new Date(date)
  if(target.getFullYear()===today.getFullYear()
      &&target.getMonth()===today.getMonth()
      &&target.getDate()===today.getDate()){
    return dayjs(date).format('HH:mm')
  }else {
    return dayjs(date).format('YYYY-MM-DD')
  }
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  queryParams.value.pageSize = size
  sysArticleList()
}

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  queryParams.value.pageNum = num
  sysArticleList()
}

//查询后台文章列表
const sysArticleList= async ()=>{
  let result= await sysArticleListService(queryParams.value)
  articles.value=result.data.items
  total.value=result.data.total
}
sysArticleList()

//查询用户文章分类列表
const categoryListByUserId= async (userId)=>{
  let result = await categoryListByUserIdService(userId)
  categorys.value=result.data
}

//重置查询表单
const resetQuery=()=>{
  queryForm.value.resetFields()
  sysArticleList()
}

//上传图片成功的回调
const uploadSuccess=(result)=>{
  articleModel.value.coverImg=result.data
}

//显示编辑文章抽屉
const showDrawer=(row)=>{
  categoryListByUserId(row.createUser)
  visibleDrawer.value=true
  title.value='修改文章'
  articleModel.value.title=row.title
  articleModel.value.username=row.user.username
  articleModel.value.categoryId=row.categoryId
  articleModel.value.coverImg=row.coverImg
  articleModel.value.content=row.content
  //扩展模型id属性
  articleModel.value.id=row.id
}

//修改文章
const updateArticle= async (state)=>{
  articleModel.value.state=state
  await updateArticleService(articleModel.value)
  ElMessage.success("修改成功")
  visibleDrawer.value=false
  sysArticleList()
}

//删除文章
const deleteArticle= (row)=>{
  ElMessageBox.confirm(
      '你确定要删除该文章吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then( async () => {
        await deleteArticleService(row.id)
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新列表
        sysArticleList()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>后台文章管理</span>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" inline >
      <el-form-item label="文章标题：" style="width: 300px" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="用户名：" style="width: 300px" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="文章分类：" style="width: 300px" prop="categoryName">
        <el-input v-model="queryParams.categoryName" placeholder="请输入文章分类"></el-input>
      </el-form-item>
      <el-form-item label="发布状态：" style="width: 300px" prop="state">
        <el-select placeholder="请选择" v-model="queryParams.state">
          <el-option label="已发布" value="已发布"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发表时间：" style="width: 300px" prop="createTime">
        <el-date-picker
            clearable
            v-model="queryParams.createTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
            size="default"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sysArticleList">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%">
      <el-table-column label="文章id" align="center" prop="id"></el-table-column>
      <el-table-column label="文章标题" align="center" prop="title"></el-table-column>
      <el-table-column label="用户名" align="center" prop="user.username"></el-table-column>
      <el-table-column label="分类" align="center" prop="category.categoryName"></el-table-column>
      <el-table-column label="图片" align="center" prop="coverImg" >
        <template #default="{ row }">
          <img :src="row.coverImg" style="width: 75px; height: 100px" @click="showImageDialog(row.coverImg)"/>
        </template>
      </el-table-column>
      <el-table-column label="文章内容" align="center" prop="content">
        <template #default="{ row }">
          <span v-if="row.content.length<= 28"> {{ row.content }} </span>
          <span v-else> {{ row.content.substring(0,25)+'...' }} </span>
        </template>
      </el-table-column>
      <el-table-column label="发表时间" align="center" prop="createTime">
        <template #default="{ row }">
          <span> {{formatDate(row.createTime)}} </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="queryParams.pageNum"
                   v-model:page-size="queryParams.pageSize"
                   :page-sizes="[3, 5 ,10, 20]"
                   layout="jumper, total, sizes, prev, pager, next"
                   background
                   :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange"
                   style="margin-top: 20px; justify-content: flex-end" />
  </el-card>
  <!-- 图片放大的对话框 -->
  <el-dialog v-model="dialogVisible" title="图片展示" center width="50%">
    <el-image :src="currentImage" style="width: 100%;height: auto"></el-image>
    <el-footer align="center">
        <el-button @click="dialogVisible=false" style="margin-top: 10px">关闭</el-button>
    </el-footer>
  </el-dialog>
  <!-- 抽屉 -->
  <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
    <!-- 修改文章表单 -->
    <el-form :model="articleModel" label-width="100px" >
      <el-form-item label="文章标题" >
        <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="用户名" >
        <el-input v-model="articleModel.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="文章分类">
        <el-select placeholder="请选择" v-model="articleModel.categoryId">
          <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面">
        <!--
        el-upload自动会发送ajax请求
        auto-upload:是否自动上传
        action:指定请求后台的url
        name:指定上传文件字段名
        headers:指定请求的请求头
        onSuccess:上传成功的回调
        -->
        <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                   action="/api/upload" name="file" :headers="{'Authorization':tokenStore.token}"
                    :on-success="uploadSuccess">
          <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容">
        <div class="editor">
          <el-input type="textarea" v-model="articleModel.content" placeholder="请输入文章内容" :rows="12"></el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateArticle('已发布')">发布</el-button>
        <el-button type="info" @click="updateArticle('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
/* 抽屉样式 */
.avatar-uploader {
  :deep {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>